
package com.sky.config;

import com.sky.constant.MessageConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
@Slf4j
@Configuration
public class RabbitMqConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback  {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @PostConstruct
    public void init()//初始化之后，RabbitTemplate 记住了“一旦将来有确认或退回事件，就去调用 this 对象的 confirm 和 returnedMessage 方法”。
    {
        log.info("Initializing RabbitTemplate callbacks");
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
        log.info("RabbitTemplate callbacks initialized");
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        //     * @param correlationData ：消息的唯一标识
        //     * @param ack ：消息确认结果
        //     * @param cause ：错误原因
        if (ack) {
            log.info("消息发送成功: correlationData={}, ack={}", correlationData, ack);
        } else {
            log.error("消息发送失败: correlationData={}, ack={}, cause={}", correlationData, ack, cause);
        }
    }
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        //发送队列失败才会调用这个函数
        //ReturnedMessage 消息对象中包括：交换机，路由key，消息内容等
        log.warn("消息被退回: exchange={}, routingKey={}, message={}",
                returnedMessage.getExchange(),
                returnedMessage.getRoutingKey(),
                new String(returnedMessage.getMessage().getBody()));
    }
    @Bean
    public MessageConverter messageConverter(){
        // 1.定义消息转换器
        Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter();
        // 2.配置自动创建消息id，用于识别不同消息，也可以在业务中基于ID判断是否是重复消息
        jackson2JsonMessageConverter.setCreateMessageIds(true);
        return jackson2JsonMessageConverter;
    }

    //正常交换机
    @Bean
    public DirectExchange normalexchange1() {
        return ExchangeBuilder.directExchange(MessageConstant.normalexchange).durable(true).build();
    }
    //死信交换机
    @Bean
    public DirectExchange sixinexchange() {
        return ExchangeBuilder.directExchange(MessageConstant.sixinexchange).durable(true).build();
    }
    @Bean
    //正常队列
    public Queue normalqueue() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("x-message-ttl", MessageConstant.MESSAGE_EXPIRE);//设置队列消息过期时间
        map.put("x-dead-letter-exchange",MessageConstant.sixinexchange);////过期的消息给哪个交换机的名字
        map.put("x-dead-letter-routing-key",MessageConstant.sixinqueque_routinkey);//交给死信交换机对应的routingkey
        return QueueBuilder.durable(MessageConstant.nomalqueue).withArguments(map).build();
    }
    //死信队列
    @Bean
    public Queue sixinqueue() {
        return QueueBuilder.durable(MessageConstant.sixinqueque).build();
    }
    //正常交换机与队列绑定
    @Bean
    public Binding bindorderexchange1withnormalqueue() {
        return BindingBuilder.bind(normalqueue()).to(normalexchange1()).with(MessageConstant.normal_routinkey);
    }
    //死信交换机与队列绑定
    @Bean
    public Binding bindsixinexchange1withsixinqueue() {
        return BindingBuilder.bind(sixinqueue()).to(sixinexchange()).with(MessageConstant.sixinqueque_routinkey);
    }

}